import { Node, Prefab } from 'cc';
import { EventName } from '../consts/events';
import Utils from '../utils';
import { Tools } from './tools';
import { getRoleTypeByName, isBulletHit } from './judge';

class Global {
    public rootBullet: Node;
    public rootEnemy: Node;
    public rootGame: Node;
    public bullet: { [key: string]: Prefab } = {};
    public isStart: boolean = false;
}

export default class Biz {
    static #score: number = 0;
    public static score = {
        getScore: () => {
            return this.#score;
        },
        addScore: (score: number) => {
            this.#score += score;
            Utils.events.emit(EventName.ScoreUpdate, this.#score);
        },
        resetScore: () => {
            this.#score = 0;
            Utils.events.emit(EventName.ScoreUpdate, this.#score);
        }
    };

    static #hp: number = 0;
    static #isInvincible: boolean = false;
    static #isPlayerDown: boolean = false;
    public static hp = {
        resetHp: (hp: number): void => {
            this.#hp = hp;
            this.#isPlayerDown = false;
            Utils.events.emit(EventName.HpUpdate, hp);
        },
        getHp: (): number => {
            return this.#hp;
        },
        subHp: (hp: number): void => {
            if (this.#isInvincible) return;
            this.#hp -= hp;
            if (this.#hp < 0) {
                this.#hp = 0;
            }
            this.#isInvincible = true;
            setTimeout(() => {
                this.#isInvincible = false;
            }, 1000);
            Utils.events.emit(EventName.HpUpdate, this.#hp);
            if (this.#hp === 0 && !this.#isPlayerDown) {
                this.#isPlayerDown = true; // 防止重复死亡
                Utils.events.emit(EventName.PlayerDown);
            } else {
                Utils.events.emit(EventName.PlayerInvincible);
            }
        },
        isInvincible: (): boolean => {
            return this.#isInvincible;
        },
        isPlayerDown: (): boolean => {
            return this.#isPlayerDown;
        }
    };

    public static global: Global = new Global();
    public static tools = Tools.instance;
    public static judge = {
        isBulletHit: isBulletHit,
        getRoleTypeByName: getRoleTypeByName
    };
}
